﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Theta.Serialization
{
    public class BinarySerializer
    {
        public static  void Serialize<T>(string path, T obj) where T : ISerializable
        {
            Stream fstream = File.Open(path, FileMode.Create);
            Serialize(fstream, obj);
        }

        public static void Serialize<T>(Stream destStream, T obj) where T : ISerializable
        {
            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter.Serialize(destStream, obj);
            destStream.Close();
        }

        public static T UnSerialize<T>(string path)
        {
            if (!File.Exists(path))
                throw new Exception("The specified file doesn't exist");
            Stream fstream = File.Open(path, FileMode.Open);
            return UnSerialize<T>(fstream);
        }

        public static T UnSerialize<T>(Stream data)
        {
            BinaryFormatter bformat = new BinaryFormatter();
            T obj = (T)bformat.Deserialize(data);
            data.Close();
            return obj;
        }
    }
}
